import React, {useCallback, useState, useRef, useEffect} from 'react';
import {
  Button,
  Divider,
  Dropdown,
  List,
  Menu,
  message, Modal,
  Result,
} from 'antd';
import {DownOutlined, LineChartOutlined, DotChartOutlined} from '@ant-design/icons';
import {getDatabaseSearchMethodText} from '../../utils/convert';
import {databaseSearch, getStatistics} from '../../network/requests';
import {CreateSpider} from '../../components/CreateSpider';
import {BookDetail} from '../../components/BookDetail';
import ComplexSearch from '../../components/ComplexSearch';
import {RelationChart} from '../../components/RelationChart';


function DatabaseSearch() {
  const [total, setTotal] = useState(0);
  const [searchItems, setSearchItems] = useState([]);
  const [loading, setLoading] = useState(false);
  const [showRelation, setShowRelation] = useState(false);
  const [page, setPage] = useState(1);
  const [loadingStatistics, setLoadingStatistics] = useState(false);
  const [noResult, setNoResult] = useState(false);
  const [createSpiderVisible, setCreateSpiderVisible] = useState(false);
  const [createSpiderKey, setCreateSpiderKey] = useState('');
  const [statistics, setStatistics] = useState(null);

  const [sortMethod, setSortMethod] = useState('comment_count');
  const [desc, setDesc] = useState(true);

  const conditions=useRef();

  const searchBooks = useCallback((page) => {
    const key=conditions.current;
    if (!key) {
      message.error('没有指定参数');
      return;
    }
    setStatistics(null);
    setLoading(true);
    databaseSearch(key, page, sortMethod, desc).then((data) => {
      setTotal(data.total);
      setSearchItems(data.data);
      setPage(data.current_page);
      if (data.total===0) {
        setNoResult(true);
      } else {
        setNoResult(false);
      }
    }).catch((e) => {
      console.log(e);
      message.error('获取图书信息失败');
    }).finally(()=>{
      setLoading(false);
    });
  }, [sortMethod, desc]);

  useEffect(()=>{
    if (conditions.current) {
      searchBooks();
    }
  }, [searchBooks]);

  const menu = (
    <Menu>
      {
        Object.entries(getDatabaseSearchMethodText).map(([key, value]) => {
          return <Menu.Item
            onClick={() => setSortMethod(key)}
            key={key}>
            {value}
          </Menu.Item>;
        })
      }
    </Menu>
  );

  const descMenu = (
    <Menu>
      <Menu.Item
        key={0}
        onClick={() => setDesc(false)}
      >升序</Menu.Item>
      <Menu.Item
        key={1}
        onClick={() => setDesc(true)}
      >降序</Menu.Item>
    </Menu>
  );

  return (
    <>
      <ComplexSearch loading={loading} setLoading={setLoading} onSearch={({searchComplex})=> {
        conditions.current=searchComplex;
        searchBooks();
      }}/>
      {
        noResult ?
          <Result status="404"
            title="还未建立索引"
            subTitle={'相关关键词还没有建立索引，可以立即创建'}
            extra={
              <Button
                onClick={
                  () => {
                    setCreateSpiderKey(conditions.current[0]?.query[0]??'');
                    setCreateSpiderVisible(true);
                  }
                } type="primary">开始爬取</Button>
            }
          /> :
          <>
            <Divider>
              搜索结果
              <Divider type={'vertical'}/>
              <Dropdown trigger={['click']} overlay={menu}>
                <Button
                  type={'link'}
                >
                  {getDatabaseSearchMethodText[sortMethod]} <DownOutlined/>
                </Button>
              </Dropdown>
              <Dropdown trigger={['click']} overlay={descMenu}>
                <Button
                  type={'link'}
                >
                  {desc ? '降序' : '升序'} <DownOutlined/>
                </Button>
              </Dropdown>
              {statistics?
                  <Button onClick={()=>{
                    setShowRelation(true);
                  }} type={'link'} icon={<DotChartOutlined/>}>
                    图书属性相关分析
                  </Button>:
                  <Button
                    onClick={()=>{
                      const key=conditions.current;
                      setLoadingStatistics(true);
                      getStatistics(key).then((data)=>{
                        data.statistics.distribution.forEach((stat)=>{
                          stat.data=stat.data.map(([key, value])=>({
                            key, value,
                          }));
                        });
                        setStatistics(data.statistics);
                        message.success('已获取数据分布');
                      }).catch(()=>{
                        message.error('获取数据分布错误');
                      }).finally(()=>{
                        setLoadingStatistics(false);
                      });
                    }}
                    disabled={searchItems.length===0}
                    loading={loadingStatistics}
                    icon={<LineChartOutlined/>} type={'link'}
                  >获取图书属性分析</Button>}
            </Divider>
            <List
              loading={loading}
              itemLayout="vertical"
              size="large"
              pagination={{
                onChange: (page) => {
                  searchBooks(page);
                  setPage(page);
                },
                pageSize: 10,
                total: total,
                position: 'bottom',
                showSizeChanger: false,
                disabled: loading,
                current: page,
              }}
              dataSource={searchItems}
              rowKey={'id'}
              renderItem={(item) => <BookDetail statistics={statistics} book={item}/>}
            />
          </>
      }
      <CreateSpider
        visible={createSpiderVisible}
        initKey={createSpiderKey}
        callback={(created, key) => {
          setCreateSpiderVisible(false);
          if (created) {
            searchSpiders(key);
          }
        }}
      />
      <Modal footer={null} visible={showRelation} onCancel={()=>{
        setShowRelation(false);
      }}>
        <RelationChart data={statistics}/>
      </Modal>
    </>
  );
}

export default DatabaseSearch;
